//
//  HBPhotoManager.m
//  HBPhotoPicker
//
//  Created by hibo on 2019/5/20.
//  Copyright © 2019 hibo. All rights reserved.
//

#import "HBPhotoManager.h"
#import "HBPhotoController.h"

static HBPhotoManager *manager;
@implementation HBPhotoManager

+(HBPhotoManager *)sharedManager{
    if (manager==nil) {
        manager = [[HBPhotoManager alloc] init];
        manager.collectionList = [NSMutableArray array];
    }
    return manager;
}
-(void)dealloc{
    NSLog(@"%@ 被释放",self.class);
}
#pragma mark - 获取所有相册
-(void)getAllCollection{
    if (_collectionList.count==0) {
        //获取相机胶卷
        PHFetchResult<PHAssetCollection *> *cameraRolls = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
        //获取个人收藏相册
        PHFetchResult<PHAssetCollection *> *favoritesCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:nil];
        //获取所有自定义相册
        PHFetchResult<PHAssetCollection *> *customCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        
        for (PHAssetCollection *collection in cameraRolls) {
            HBAlbumModel *model = [[HBAlbumModel alloc] init];
            model.collection = collection;
            model.maxCount = _maxCount==0?9:_maxCount;
            if (model.number>0) {
                [_collectionList addObject:model];
            }
        }
        for (PHAssetCollection *collection in favoritesCollections) {
            HBAlbumModel *model = [[HBAlbumModel alloc] init];
            model.collection = collection;
            model.maxCount = _maxCount==0?9:_maxCount;
            if (model.number>0) {
                [_collectionList addObject:model];
            }
        }
        for (PHAssetCollection *collection in customCollections) {
            HBAlbumModel *model = [[HBAlbumModel alloc] init];
            model.collection = collection;
            model.maxCount = _maxCount==0?9:_maxCount;
            if (model.number>0) {
                [_collectionList addObject:model];
            }
        }
    }
}
#pragma mark - 显示图片选择器
+(void)showPhotoControllerType:(HBPhotoSelectType)type maxCount:(NSInteger)maxCount result:(void(^)(NSArray *assets))block{
    HBPhotoManager *mananer = [HBPhotoManager sharedManager];
    mananer.selectType = type;
    mananer.maxCount = maxCount==0?9:maxCount;
    [mananer getAllCollection];//获取图片激活权限提示
    UIViewController *controller = [UIApplication sharedApplication].delegate.window.rootViewController;
    //获取图片权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status==PHAuthorizationStatusRestricted||status==PHAuthorizationStatusDenied) {
        NSLog(@"相册权限受限");
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"相册权限受限是否去设置" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }]];
        [controller presentViewController:alert animated:YES completion:nil];
    }else if(status==PHAuthorizationStatusNotDetermined){
        
    }else{
        HBPhotoController *albumController = [[HBPhotoController alloc] init];
        albumController.photoManager = mananer;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:albumController];
        [controller presentViewController:nav animated:YES completion:nil];
        albumController.selectResult = ^(id  _Nonnull result) {
            block(result);
        };
    }
}

#pragma mark - 获取图片信息
+(void)getPhotoInfoWithAsset:(PHAsset*)asset targetSize:(CGSize)targetSize result:(void(^)(UIImage *image,PHAssetMediaType mediaType))block{
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = NO;//同步获得图片，只会返回1张图片 只返回一个结果，阻塞直到可用（或失败）。默认为否
    [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        block(result,asset.mediaType);
    }];
}
@end


